﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Petroleum.UI.Tool.Office
{
    /// <summary>
    /// 注册和取消注册：dsoframer.ocx
    /// </summary>
    public class OcxRegister
    {
        /// <summary>
        /// 判断是否注册了dsoframer.ocx
        /// </summary>
        /// <returns>true表示已经注册过</returns>
        public static bool IsRegisted()
        {
            bool isRegisted = IsRegistered("00460182-9E5E-11D5-B7C8-B8269041DD57");
            return isRegisted;
        }



        /// <summary>
        /// 注册dsoframer.ocx
        /// </summary>
        /// <returns>返回-1：注册失败；返回1：注册成功；返回2：已注册过，不用重复注册</returns>
        public static int RegisterMain()
        {
            // 存放ocx文件的目录： bin\Debug\ocx\dsoframer.ocx
            string fileFullPath = string.Format("{0}\\ocx\\dsoframer.ocx", System.Environment.CurrentDirectory);
            string systemDrive = System.Environment.GetEnvironmentVariable("systemdrive");//获取系统所在的盘符
            // 确保dsoframer.ocx存在
            if (!File.Exists(fileFullPath) || String.IsNullOrEmpty(systemDrive))
                return -1; // dsoframer.ocx不存在，注册失败
            bool isRegisted = IsRegistered("00460182-9E5E-11D5-B7C8-B8269041DD57");
            if (isRegisted)
                return 2; // 已注册过，注册成功

            string windowsPath = string.Empty;
            if (GetOSBitCount() == "64")
                windowsPath = string.Format("{0}\\Windows\\SysWOW64", systemDrive);
            else
                windowsPath = string.Format("{0}\\Windows\\System32", systemDrive);
            if (!Directory.Exists(windowsPath))
                return -1;//目标目录不存在，注册失败
            // 复制dsoframer.ocx文件到C:\\Windows\\SysWOW64 或 C:\\Windows\\System32
            File.Copy(fileFullPath, string.Format("{0}\\dsoframer.ocx", windowsPath), true);

            bool result = Registe(string.Format("{0}\\dsoframer.ocx", windowsPath)); //开始注册

            if (result)
            {
                return -1; //注册失败
            }
            return 1;//注册成功
        }

        /// <summary>
        /// 取消注册dsoframer.ocx
        /// </summary>
        /// <returns></returns>
        public static bool UnRegisterMain()
        {
            // 存放ocx文件的目录： bin\Debug\ocx\dsoframer.ocx
            string fileFullPath = string.Format("{0}\\ocx\\dsoframer.ocx", System.Environment.CurrentDirectory);
            string systemDrive = System.Environment.GetEnvironmentVariable("systemdrive");//获取系统所在的盘符
            string windowsPath = string.Empty;
            if (GetOSBitCount() == "64")
                windowsPath = string.Format("{0}\\Windows\\SysWOW64", systemDrive);
            else
                windowsPath = string.Format("{0}\\Windows\\System32", systemDrive);
            File.Copy(fileFullPath, string.Format("{0}\\dsoframer.ocx", windowsPath), true);

            bool isRegisted = IsRegistered("00460182-9E5E-11D5-B7C8-B8269041DD57");
            bool result = false;
            if (isRegisted)
            {
                result = UnRegiste(string.Format("{0}\\dsoframer.ocx", windowsPath));//取消注册
                result = !result;
            }
            return result;
        }

        //注册dsoframer.ocx  
        private static bool Registe(string fileFullName)
        {
            bool result = false;
            System.Diagnostics.Process p = System.Diagnostics.Process.Start("regsvr32", fileFullName + " /s");//注册完毕不显示是否成功的提示  
            //System.Diagnostics.Process p = System.Diagnostics.Process.Start("regsvr32", fileFullName);//注册完毕显示是否成功的提示  
            if (p != null && p.HasExited)
            {
                Int32 exitCode = p.ExitCode;
                if (exitCode == 0)
                    result = true;
            }
            return result;//成功时，返回false
        }

        //取消注册dsoframer.ocx
        private static bool UnRegiste(string fileFullName)
        {
            bool result = false;
            System.Diagnostics.Process p = System.Diagnostics.Process.Start("regsvr32", fileFullName + " /u");//取消注册
            if (p != null && p.HasExited)
            {
                Int32 exitCode = p.ExitCode;
                if (exitCode == 0)
                    result = true;
            }
            return result;//成功时，返回false
        }

        //获取当前操作系统的位数 :需要添加引用System.Management
        private static string GetOSBitCount()
        {
            ConnectionOptions oConn = new ConnectionOptions();
            System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);
            System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();
            string addressWidth = null;

            foreach (ManagementObject oReturn in oReturnCollection)
                addressWidth = oReturn["AddressWidth"].ToString();

            return addressWidth;
        }

        //判断控件是否已经注册  
        private static bool IsRegistered(String CLSID)
        {
            if (String.IsNullOrEmpty(CLSID))
                return false;

            String key = String.Format(@"CLSID\{{{0}}}", CLSID);
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(key);
            if (regKey != null)
                return true;
            else
                return false;
        }
    }
}
